package cn.vacuumflask.cordova;

import android.app.Activity;
import android.app.ProgressDialog;
import android.text.TextUtils;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.dascom.print.SmartPrint;

import cn.vacuumflask.cordova.entity.PrintOrder;
import cn.vacuumflask.cordova.utils.L;
import cn.vacuumflask.cordova.utils.WiFiPrintUtil;

/**
 * Created by huangqx on 2017-10-18.
 */

public class ContactInfo {

    private Activity activity;
    private PrintOrder order;
    private SmartPrint smartPrint;
    private ProgressDialog progressDialog;


    public ContactInfo(Activity act, SmartPrint smartPrint, ProgressDialog progressDialog) {
        this.activity = act;
        this.smartPrint = smartPrint;
        this.progressDialog = progressDialog;
        order = new PrintOrder();
    }

    public boolean printOrder(String json) {

        L.json(json);

        json = json.trim();

        order = JSON.parseObject(json, PrintOrder.class);

        if (order != null) {
            String ptintIp = order.getPtintIp();
            if (!TextUtils.isEmpty(ptintIp)) {
                if (!ptintIp.contains(":9100")) {
                    ptintIp = ptintIp + ":9100";
                }
                linkPrint(ptintIp);
                return true;
            } else {
                Toast.makeText(activity, "打印失败", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(activity, "打印机连接失败", Toast.LENGTH_SHORT).show();
        }

        return false;
    }


    private void linkPrint(String ipData) {
        if (!smartPrint.DSWifiState()) {//判断是否连接WiFi
            //没连接输入IP进行连接
            smartPrint.DSSetWifiConnectTimeout(20000);//设置 WIFI连接超时的时间
            smartPrint.DSLinkWifi(ipData);//连接指定的 WiFi 设备
        } else {
            //已经连接就直接打印
            printBill();
        }
    }


    public void printBill() {
        WiFiPrintUtil.printOrder(activity, smartPrint, order, progressDialog);//打印入库单
    }


}
